<template>
  <!-- 弹窗 -->
  <el-dialog :title="title" v-model="props.visible" width="1436px" :before-close="handleClose" @opened="initMap">
    <div class="dialog-map">
      <div flex justify-end style="margin-bottom: 10px; align-items: center" @click="startCarTrack">
        <div flex style="align-items: center">
          <div>轨迹播放</div>
          <div class="back-btn" />
        </div>
        <!-- <div @click="pauseCarTrack" value="暂停" style="margin-left: 10px">播放暂停</div>
          <div @click="stopCarTrack" value="结束" style="margin-left: 10px">结束播放</div> -->
        <!-- <input type="button" value="暂停" @click="pauseCarTrack" />
          <input type="button" value="结束" @click="stopCarTrack" /> -->
      </div>

      <div flex justify-end style="margin-bottom: 10px; align-items: center">
        <!-- <input type="button" value="开始" @click="startCarTrack" /> -->
        <input type="button" value="暂停" @click="pauseCarTrack" />
        <input type="button" value="结束" @click="stopCarTrack" style="margin-left: 10px" />
      </div>
      <div ref="mapDiv" class="map-container" />
    </div>
    <div class="dialog-table">
      <div class="table-list">
        <div class="table-title">车牌信息</div>
        <div v-for="(item, index) in ownerInfo" :key="index" class="owner-info">
          <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px">{{ item.ownerName }}</div>
          <div>{{ item.licensePlate }}</div>
        </div>
      </div>
      <div class="table-list" style="height: 132px">
        <div class="table-title">车牌信息</div>
        <div v-for="(item, index) in alarmInfo" :key="index" class="owner-info">
          <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px; width: 75px">{{ item.alarmTime }}</div>
          <div>{{ item.alarmLocation }}</div>
        </div>
      </div>
      <div class="table-list" style="height: 131px">
        <div class="table-title">处理信息</div>
        <div class="owner-info">
          <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px">处理结果：</div>
          <div>
            <el-radio-group v-model="radio1">
              <el-radio value="1" size="large">真实报警</el-radio>
              <el-radio value="2" size="large">误报</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div flex>
          <div style="color: rgba(0, 0, 0, 0.4); margin-right: 12px">处理描述：</div>
          <el-input v-model="textarea" style="width: 240px" :rows="2" type="textarea" placeholder="这是一段文字描述" />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue"
// 弹窗相关
const dialogVisible = ref(false)
import start from "../../../../assets/images/icon-statrt.svg"
import end from "../../../../assets/images/icon-end.svg"
const radio1 = ref(1)
const textarea = ref("")
const ownerInfo = ref([
  {
    ownerName: "车主姓名：",
    licensePlate: "钱浩均"
  },
  {
    ownerName: "车牌号码：",
    licensePlate: "渝CD522Q"
  },
  {
    ownerName: "运输证号：",
    licensePlate: "斯巴鲁"
  },
  {
    ownerName: "车主手机：",
    licensePlate: "15246978726"
  },
  {
    ownerName: "经营区域：",
    licensePlate: "福建省厦门市海沧区"
  },
  {
    ownerName: "从业资格证号：",
    licensePlate: "411520181"
  }
])
const alarmInfo = ref([
  {
    alarmTime: "报警时间：",
    alarmLocation: "2024-09-19 22:38:20"
  },
  {
    alarmTime: "报警地点：",
    alarmLocation: "甘肃省临夏回族自治州康乐县"
  },
  {
    alarmTime: "报警描述：",
    alarmLocation: "作业外出车"
  },
  {
    alarmTime: "报警证据：",
    alarmLocation: "暂未提供证据"
  }
])

const props = defineProps({
  visible: Boolean,
  title: String, // 接收传递过来的标题
  data: Array
})

const emit = defineEmits(["update:visible"])

function handleClose() {
  emit("update:visible", false)
}
//引入天地图
let map: any
let drivingRoute: any
let _CarTrack: any

const zoom = 14
const startIcon = start
const endIcon = end

const initMap = async () => {
  const T = window.T

  if (!T) {
    console.error("T is not defined. Make sure the TianDiTu SDK is loaded correctly.")
    return
  }

  // 等待 DOM 更新完成
  await nextTick()

  const mapDiv = document.querySelector(".map-container")
  if (!mapDiv) {
    console.error("mapDiv does not exist")
    return
  }

  // 初始化地图
  map = new T.Map(mapDiv, "EPSG:4326")

  // 设置地图中心点和缩放级别
  map.centerAndZoom(new T.LngLat(103.85264, 30.06813), zoom)

  // 添加缩放平移控件
  const control = new T.Control.Zoom()
  map.addControl(control)

  // 调用 Geolocation API 定位当前所在地
  // locateCurrentPosition()

  // 添加驾车路线搜索配置
  const config = {
    policy: 0, // 驾车策略
    onSearchComplete: searchResult // 检索完成后的回调函数
  }

  // 初始化驾车路线搜索服务
  drivingRoute = new T.DrivingRoute(map, config)

  // 执行驾车路线搜索
  searchDrivingRoute()
}

// 定位当前所在地
const locateCurrentPosition = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const currentLng = position.coords.longitude
        const currentLat = position.coords.latitude
        console.log("Current position:", currentLng, currentLat)

        // 将地图中心点设置为当前位置
        map.centerAndZoom(new T.LngLat(currentLng, currentLat), zoom)
      },
      (error) => {
        console.error("Error getting current location:", error)
      },
      {
        enableHighAccuracy: true, // 提高精度
        timeout: 10000, // 超时时间
        maximumAge: 0 // 不使用缓存的位置信息
      }
    )
  } else {
    console.error("Geolocation is not supported by this browser.")
  }
}

// 搜索驾车路线
const searchDrivingRoute = () => {
  map.clearOverLays()

  const startLngLat = new T.LngLat(103.83522, 30.08477)
  const endLngLat = new T.LngLat(103.84964, 30.0578)
  const problematicStart = new T.LngLat(103.84749, 30.07452) // 问题起点
  const problematicEnd = new T.LngLat(103.84865, 30.06074) // 问题终点

  // 驾车路线搜索
  drivingRoute.search(startLngLat, endLngLat)
}

// 创建路线
const createRoute = (lnglats, lineColor = "#059669") => {
  if (!Array.isArray(lnglats) || lnglats.length < 2) {
    console.error("lnglats must be a valid array with at least two points.")
    return
  }

  console.log("Creating CarTrack with coordinates:", lnglats)
  _CarTrack = new T.CarTrack(map, {
    interval: 20,
    speed: 10,
    dynamicLine: true,
    Datas: lnglats,
    polylinestyle: { color: lineColor, width: 6, opacity: 0.9 }
  })

  console.log("CarTrack created:", _CarTrack)
}

// 添加起始点标记
const createStartMarker = (result) => {
  const startMarker = new T.Marker(result.getStart(), {
    icon: new T.Icon({
      iconUrl: startIcon,
      iconSize: new T.Point(44, 34),
      iconAnchor: new T.Point(12, 31)
    })
  })
  map.addOverLay(startMarker)

  const endMarker = new T.Marker(result.getEnd(), {
    icon: new T.Icon({
      iconUrl: endIcon,
      iconSize: new T.Point(44, 34),
      iconAnchor: new T.Point(12, 31)
    })
  })
  map.addOverLay(endMarker)
}

// 路线搜索完成的回调
const searchResult = (result) => {
  createStartMarker(result)

  const routes = result.getNumPlans()
  for (let i = 0; i < routes; i++) {
    const plan = result.getPlan(i)
    // 创建原有路线
    const path = plan.getPath()
    createRoute(path)

    // 在原有线路的基础上，添加问题红色线路
    addProblematicRoute(path, new T.LngLat(103.84749, 30.07452), new T.LngLat(103.84865, 30.06074))
  }
}

// 创建问题线路
const addProblematicRoute = (originalPath, problematicStart, problematicEnd) => {
  // 查找原有路径中，问题起点和终点的索引
  const startIndex = originalPath.findIndex(
    (point) => point.lng === problematicStart.lng && point.lat === problematicStart.lat
  )
  const endIndex = originalPath.findIndex(
    (point) => point.lng === problematicEnd.lng && point.lat === problematicEnd.lat
  )

  if (startIndex === -1 || endIndex === -1 || startIndex > endIndex) {
    console.error("Invalid problematic segment.")
    return
  }

  // 获取红色线路的起点和终点之间的所有点
  const problematicSegment = originalPath.slice(startIndex, endIndex + 1)

  // 创建红色线路
  createRoute(problematicSegment, "red")

  // 在问题线路的起点和终点添加标记
  addMarker(problematicStart, "问题起点")
  addMarker(problematicEnd, "问题终点")
}

// 添加标记的函数
const addMarker = (lngLat, info) => {
  const marker = new T.Marker(lngLat, {
    icon: new T.Icon({
      iconUrl: "your_icon_url.png", // 这里可以放置信息图标的URL
      iconSize: new T.Point(20, 20),
      iconAnchor: new T.Point(10, 10)
    })
  })

  // 点击事件展示问题信息
  marker.addEventListener("click", () => {
    alert(`问题信息: ${info}`) // 替换为实际展示逻辑
  })

  map.addOverLay(marker)
}

// 控制按钮函数
const startCarTrack = () => _CarTrack?.start()
const pauseCarTrack = () => _CarTrack?.pause()
const stopCarTrack = () => _CarTrack?.stop()
</script>

<style scoped lang="scss">
.dialog-map {
  cursor: pointer;
  width: 1018px;
  height: 740px;
  .back-btn {
    width: 22px;
    height: 22px;
    background-image: url("../../../../assets/images/icon-bo.png");
    background-size: 100% 100%;
    background-repeat: no-repeat; /* 防止图片重复 */
    margin-left: 5px;
  }
}
.dialog-table {
  width: 50%;
  height: 589px;
  margin-left: 38px;

  .table-list {
    width: 334px;
    height: 188px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-bottom: 59px;
    .table-title {
      font-family: AlibabaPuHuiTi20;
      font-weight: 600;
      font-size: 14px;
      color: #000000;
      margin-bottom: 8px;
    }
    .owner-info {
      display: flex;
      align-items: center;
    }
  }
}
.map-container {
  width: 1018px;
  height: 680px;
  border-radius: 8px 8px 8px 8px;
  border: 1px solid #e4e4e7;
}
</style>
